package com.shuaiche.yeguan.ui.select;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.SCApplication;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCUserInfoConfig;
import com.shuaiche.yeguan.model.SCAllUserListResponse;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.util.StringUtils;
import com.shuaiche.yeguan.util.pinyinhelper.Pinyin;
import com.shuaiche.yeguan.views.brandselectbar.ItemBean;
import com.shuaiche.yeguan.views.brandselectbar.decoration.DividerItemDecoration;
import com.shuaiche.yeguan.views.brandselectbar.decoration.TitleItemDecoration;
import com.shuaiche.yeguan.views.brandselectbar.widget.IndexBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class SCPurchaserSelectActivity extends AppCompatActivity implements View.OnClickListener {

    private RecyclerView mRv;
    private SCPurchaserSelectAdapter mAdapter;
    private LinearLayoutManager mManager;
    private List<ItemBean> mDatas = new ArrayList<>();
    private TitleItemDecoration mDecoration;

    private TextView tvPurchaser;   //已售车辆 搜索时显示
    /**
     * 右侧边栏导航区域
     */
    private IndexBar mIndexBar;

    /**
     * 显示指示器DialogText
     */
    private TextView mTvSideBarHint;

    private Long unionId;       //联盟id
    private Long merchantId;    //商户id
    private Long purchaserId;   //收购员id

    private List<SCAllUserListResponse> users;
    private boolean isFromUnion = false;    //联盟库存跳转进来
    private boolean isFromSold = false;     //已售列表中跳转进入

    private String title;
    private String from;

    private TextView tv_title;
    private RelativeLayout rl_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        );
        setContentView(R.layout.activity_scpurchaser_select);
        getData();

        mRv = (RecyclerView) findViewById(R.id.rv);
        mRv.setLayoutManager(mManager = new LinearLayoutManager(this));

        tvPurchaser = (TextView) findViewById(R.id.tvPurchaserSelect);

        //使用indexBar
        mTvSideBarHint = (TextView) findViewById(R.id.tvSideBarHint);//HintTextView
        mIndexBar = (IndexBar) findViewById(R.id.indexBar);//IndexBar
        tv_title = findViewById(R.id.tv_title);
        rl_back = findViewById(R.id.rl_back);
        rl_back.setOnClickListener(this);


        tv_title.setText(title);
//        if (isFromSold || isFromUnion) {
//            tvPurchaser.setVisibility(View.VISIBLE);
//            tvPurchaser.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    for (int i = 0; i < mDatas.size(); i++) {
//                        mDatas.get(i).setSelect(false);
//                    }
//                    Intent intent = new Intent();
//                    intent.putExtra("users", new ItemBean());
//                    finishActivity(Activity.RESULT_OK, intent);
//                }
//            });
//        } else {
//            tvPurchaser.setVisibility(View.GONE);
//        }

        getUserList();
    }

    private void getData() {
        if (getIntent() != null) {

            title = getIntent().getStringExtra("title");
            from = getIntent().getStringExtra("from");
        }


    }

    private void setView() {
        mAdapter = new SCPurchaserSelectAdapter(this, mDatas);
        mRv.setAdapter(mAdapter);
        mAdapter.setCallbackListener(new SCPurchaserSelectAdapter.CallbackListener() {
            @Override
            public void itemClick(int position) {
                for (int i = 0; i < mDatas.size(); i++) {
                    mDatas.get(i).setSelect(false);
                }
                mDatas.get(position).setSelect(true);
                mAdapter.notifyDataSetChanged();

                Intent intent = new Intent();
                intent.putExtra("users", mDatas.get(position));

                try {
                    ReactContext reactContext =  SCApplication.getApplication().getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
                    if (reactContext == null) {
                        return;
                    }
                    WritableMap event = Arguments.createMap();
                    /**
                     * {"userId":106700175,"phone":"13666698569","fullname":"项坚测试"}
                     */
                    event.putDouble("userId", mDatas.get(position).getId());
                    event.putString("fullname", mDatas.get(position).getName()+"");
                    event.putString("type", "selectUserResult");
                    event.putString("from", from);

                    reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("commonEvent", event);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                finish();
//                finishActivity(Activity.RESULT_OK, intent);
            }
        });
        mRv.addItemDecoration(mDecoration = new TitleItemDecoration(this, mDatas));
        mRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mIndexBar.setmPressedShowTextView(mTvSideBarHint)//设置HintTextView
                .setNeedRealIndex(false)//设置需要真实的索引
                .setmLayoutManager(mManager)//设置RecyclerView的LayoutManager
                .setmSourceDatas(mDatas);//设置数据源
    }


    private void getUserList(){
        Map<String, Object> params = new HashMap<>();
        params.put("merchantId", SCUserInfoConfig.getUserinfo().getMerchantId());
        HttpHelper.getInstance().appendUrl(HttpUrl.GET_USER_BY_MERCHANTID)
                .addGetParam(params).get(new HttpCallBack<SCAllUserListResponse>(this) {
            @Override
            public void onSuccessed(SCAllUserListResponse result) {
                users = (List<SCAllUserListResponse>)result.getData();
                if (users != null && users.size() > 0) {
                    for (SCAllUserListResponse user : users) {
                        ItemBean itemBean = new ItemBean();
                        if (StringUtils.isEmpty(user.getFullname())) {
                            itemBean.setName(SCUserInfoConfig.getUserinfo().getUsername());
                            itemBean.setHeadLetter(Pinyin.toPinyin(SCUserInfoConfig.getUserinfo().getUsername().charAt(0)));
                        } else {
                            itemBean.setName(user.getFullname());
                            itemBean.setHeadLetter(Pinyin.toPinyin(user.getFullname().charAt(0)));
                        }
                        itemBean.setId(user.getUserId());

                        if (user.getUserId().equals(purchaserId)) {
                            itemBean.setSelect(true);
                        }
                        itemBean.setHeadLetter(itemBean.getHeadLetter().toUpperCase());
                        mDatas.add(itemBean);
                    }
                }
                setView();
            }

            @Override
            public void onFailured(String errorCode, String errMsg) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_back){
            finish();
        }
    }
}